package com.zrz.util;

import com.google.gson.Gson;
import com.zrz.domain.ImageUpload;
import com.zrz.wechart.WeixinOauth2Token;
import com.zrz.wechart.WeixinUtil;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class UploadImageUitl {
    public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";// 获取access
    public static final String UPLOAD_IMAGE_URL = "http://file.api.weixin.qq.com/cgi-bin/media/upload";// 上传多媒体文件
    public static final String APP_ID = "wx90fa698910b7b66c";
    public static final String SECRET = "c9e33765c9ed958c3e23eb68e20fc2dc";

    public static  ImageUpload uploadTempMedia(String appId,String secret,String name) {
        try{
        File file = ResourceUtils.getFile("classpath:"+name);
        //设置消息请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data;charset=UTF-8");//multipart/form-data  text/plain
        headers.setContentType(type);
        FileSystemResource resource = new FileSystemResource(file);
        //将文件作为参数添加
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("resource", resource);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
        // 获取accesstoken（这是我封装的accesstoken实体对象，可根据具体情况自行获取accesstoken）
        WeixinOauth2Token weixinOauth2Token = WeixinUtil.getAccessToken(appId, secret);
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + weixinOauth2Token.getAccessToken() + "&type=image";
        RestTemplate restTemplate = new RestTemplate();
        // 进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        // 解析返回值（返回json）
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            ImageUpload imageUpload=new Gson().fromJson(sessionData,ImageUpload.class);
            return imageUpload;
        } else {
            return null;
        }
        }catch (Exception e){
            return null;
        }
    }
    public static  ImageUpload uploadTempMediaByUrl(String appId,String secret,String imageUrl) {
        try{
            File file = new File(imageUrl);
            //设置消息请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("multipart/form-data;charset=UTF-8");//multipart/form-data  text/plain
            headers.setContentType(type);
            FileSystemResource resource = new FileSystemResource(file);
            //将文件作为参数添加
            MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
            map.add("resource", resource);
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
            // 获取accesstoken（这是我封装的accesstoken实体对象，可根据具体情况自行获取accesstoken）
            WeixinOauth2Token weixinOauth2Token = WeixinUtil.getAccessToken(appId, secret);
            String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + weixinOauth2Token.getAccessToken() + "&type=image";
            RestTemplate restTemplate = new RestTemplate();
            // 进行网络请求,访问url接口
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            // 解析返回值（返回json）
            if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                String sessionData = responseEntity.getBody();
                ImageUpload imageUpload=new Gson().fromJson(sessionData,ImageUpload.class);
                return imageUpload;
            } else {
                return null;
            }
        }catch (Exception e){
            return null;
        }
    }

    public static  String getTempMedia(String media_id) {
        // 获取accesstoken（可根据情况自行获取accesstoken）
        WeixinOauth2Token weixinOauth2Token = WeixinUtil.getAccessToken(APP_ID, SECRET);
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+weixinOauth2Token.getAccessToken()+"&media_id="+media_id;
        RestTemplate restTemplate = new RestTemplate();
        // 进行网络请求,访问url接口
        ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
        // 解析返回值（请求成功返回图片二进制流，失败返回错误信息json）
        if (responseEntity!=null&&responseEntity.getStatusCode()==HttpStatus.OK) {
            byte[] sessionData = responseEntity.getBody();
            try {
                for (int i = 0; i<sessionData.length; ++i) {
                    if (sessionData[i]<0) {// 调整异常数据
                        sessionData[i] += 256;
                    }
                }
                // 生成jpg图片
                String savePath = "d://image/";// 新生成的图片
                if (!savePath.endsWith("/")) {
                    savePath += "/";
                }
                // 根据内容类型获取扩展名
                String fileExt = responseEntity.getHeaders().getContentType().getSubtype();
                // 将mediaId作为文件名
                String filePath = savePath + media_id + "." + fileExt;
                OutputStream out = new FileOutputStream(filePath);
                out.write(sessionData);
                out.flush();
                out.close();
                return filePath;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String arg[]) {
        UploadImageUitl test=new UploadImageUitl();
        System.out.println(test.uploadTempMedia("wx90fa698910b7b66c","c9e33765c9ed958c3e23eb68e20fc2dc","guanzhu.jpg"));
//        test.getTempMedia("5gri3HPYcWHAXZ2BUhjQ2fI9EmTe2m9OlOfJpT8xskj2TfxZ_JwxEr5T-6nJeQUh");
    }


}
